package com.training.web.controller;

import com.training.bean.User;
import com.training.base.Result;
import com.google.gson.Gson;
import com.training.base.ResponseUtils;
import com.training.jwt.JWTUtils;
import com.training.utils.FileUploadUtil;
import com.training.utils.MD5Util;
import com.training.utils.UrlUtils;
import com.training.web.service.WebUserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api/web/user")
public class WebUserController {

    @Autowired
    private WebUserService webUserService;
    @Autowired
    private FileUploadUtil fileUploadUtil;
    @Autowired
    private Gson gson;
    @Autowired
    private ResponseUtils responseUtils;
    
    // 默认头像路径
    private static final String DEFAULT_AVATAR_PATH = "/images/default-avatar.png";

    /**
     * 获取所有用户（后台管理专用）
     * @return 用户列表结果
     */
    @GetMapping("/getAll")
    public ResponseEntity<Result<List<User>>> getAllUsers(HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int userId = JWTUtils.getUserIdFromRequest(request);
            
            // 如果无法获取用户ID，则返回错误
            if (userId == -1) {
                return responseUtils.failWithType(401, "无法获取用户身份信息");
            }
            
            List<User> users = webUserService.getAllUsers();
            return responseUtils.success(users, "获取用户列表成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.failWithType(500, "获取用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据手机号搜索用户（后台管理专用）
     * @param phone 手机号
     * @return 搜索结果
     */
    @GetMapping("/search")
    public ResponseEntity<Result<List<User>>> searchUsers(@RequestParam String phone, HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int userId = JWTUtils.getUserIdFromRequest(request);
            
            // 如果无法获取用户ID，则返回错误
            if (userId == -1) {
                return responseUtils.failWithType(401, "无法获取用户身份信息");
            }
            
            List<User> users = webUserService.searchUsersByPhone(phone);
            return responseUtils.success(users, "搜索用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.failWithType(500, "搜索用户失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户ID搜索用户（后台管理专用）
     * @param id 用户ID
     * @return 搜索结果
     */
    @GetMapping("/search/{id}")
    public ResponseEntity<Result<User>> searchUser(@PathVariable int id, HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int userId = JWTUtils.getUserIdFromRequest(request);
            
            // 如果无法获取用户ID，则返回错误
            if (userId == -1) {
                return responseUtils.failWithType(401, "无法获取用户身份信息");
            }
            
            User user = webUserService.searchUsersById(id);
            return responseUtils.success(user, "搜索用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.failWithType(500, "搜索用户失败: " + e.getMessage());
        }
    }

    /**
     * 添加用户（后台管理专用）
     * @param nickname 用户昵称
     * @param phone 手机号
     * @param password 密码
     * @param avatarFile 头像文件
     * @param request HTTP请求对象
     * @return 添加结果
     */
    @PostMapping("/addUser")
    public ResponseEntity<Result<User>> addUser(@RequestParam(name = "nickname") String nickname,
                          @RequestParam(name = "phone") String phone,
                          @RequestParam(name = "password") String password,
                          @RequestParam(value = "avatar", required = false) MultipartFile avatarFile,
                          HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int userId = JWTUtils.getUserIdFromRequest(request);
            
            // 如果无法获取用户ID，则返回错误
            if (userId == -1) {
                return responseUtils.failWithType(401, "无法获取用户身份信息");
            }
            
            // 创建用户对象
            User user = new User();
            user.nickname = nickname;
            user.phone = phone;
            user.password = password;
            user.course_count = 0;
            user.study_date = 0;
            user.collect_count = 0;
            user.setDisabled(false);
            // 处理上传的头像文件
            String fileUrl = null;
            if (avatarFile != null && !avatarFile.isEmpty()) {
                fileUrl = fileUploadUtil.uploadAvatar(avatarFile);
            }
            if (fileUrl != null) {
                user.avatar = fileUrl;
            }

            // 添加用户
            User savedUser = webUserService.addUser(user, request);

            if (savedUser != null) {
                // 动态构建完整头像URL
                if (savedUser.avatar != null && !savedUser.avatar.isEmpty()) {
                    savedUser.avatar = UrlUtils.buildFullUrl(request, savedUser.avatar);
                } else {
                    // 如果没有头像，使用默认头像
                    savedUser.avatar = UrlUtils.buildFullUrl(request, "/images/default-avatar.png");
                }
                return responseUtils.success(savedUser, "用户添加成功");
            } else {
                return responseUtils.failWithType(500, "用户添加失败");
            }
        } catch (Exception e) {
            // 构造失败的结果对象
            return responseUtils.failWithType(500, "用户添加失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息（后台管理专用）
     * @param id 用户ID
     * @param nickname 用户昵称
     * @param phone 手机号
     * @param password 密码
     * @param avatarFile 头像文件
     * @param request HTTP请求对象
     * @return 更新结果
     */
    @PostMapping("/updateUser")
    public ResponseEntity<Result<User>> updateUser(@RequestParam(name = "id") int id,
                             @RequestParam(name = "nickname") String nickname,
                             @RequestParam(name = "phone") String phone,
                             @RequestParam(name = "password", required = false) String password,
                             @RequestParam(value = "avatar", required = false) MultipartFile avatarFile,
                             @RequestParam(value = "avatarWidth", defaultValue = "200") int avatarWidth,
                             @RequestParam(value = "avatarHeight", defaultValue = "200") int avatarHeight,
                             HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int userId = JWTUtils.getUserIdFromRequest(request);
            
            // 如果无法获取用户ID，则返回错误
            if (userId == -1) {
                return responseUtils.failWithType(401, "无法获取用户身份信息");
            }
            
            // 查找现有用户
            User user = webUserService.findUserById(id);
            if (user==null) {
                return responseUtils.failWithType(500, "用户不存在");
            }
            // 保存旧头像URL，以便在更新后删除
            String oldAvatarUrl = user.avatar;

            // 更新用户基本信息
            user.nickname = nickname;
            user.phone = phone;

            // 只有当提供了新密码时才更新密码
            if (password != null && !password.isEmpty()) {
                user.password = MD5Util.encrypt(password);
            }

            // 处理上传的新头像文件
            String fileUrl = null;
            if (avatarFile != null && !avatarFile.isEmpty()) {
                // 如果指定了头像尺寸，则进行裁剪
                if (avatarWidth > 0 && avatarHeight > 0) {
                    fileUrl = fileUploadUtil.uploadAndCropAvatar(avatarFile, avatarWidth, avatarHeight);
                } else {
                    fileUrl = fileUploadUtil.uploadAvatar(avatarFile);
                }
                if (fileUrl != null) {
                    user.avatar = fileUrl;
                }
            }

            // 更新用户信息
            User updatedUser = webUserService.updateUser(user);

            // 如果上传了新头像且旧头像存在，则删除旧头像文件
            if (fileUrl != null && oldAvatarUrl != null && !oldAvatarUrl.isEmpty() && !oldAvatarUrl.equals(fileUrl)) {
                fileUploadUtil.deleteFile(oldAvatarUrl);
            }

            // 动态构建完整头像URL
            if (updatedUser.avatar != null && !updatedUser.avatar.isEmpty()) {
                updatedUser.avatar = UrlUtils.buildFullUrl(request, updatedUser.avatar);
            } else {
                // 如果没有头像，使用默认头像
                updatedUser.avatar = UrlUtils.buildFullUrl(request, "/images/default-avatar.png");
            }

            return responseUtils.success(updatedUser, "用户更新成功");
        } catch (Exception e) {
            // 构造失败的结果对象
            return responseUtils.failWithType(500, "用户更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户（后台管理专用）
     * @param userId 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/deleteUser/{userId}")
    public ResponseEntity<Result<Object>> deleteUser(@PathVariable int userId, HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int userIdFromToken = JWTUtils.getUserIdFromRequest(request);
            
            // 如果无法获取用户ID，则返回错误
            if (userIdFromToken == -1) {
                return responseUtils.fail(401, "无法获取用户身份信息");
            }
            
            // 删除用户
            boolean deleted = webUserService.deleteUser(userId);

            if (deleted) {
                return responseUtils.success(null, "用户删除成功");
            } else {
                return responseUtils.fail(500, "用户删除失败");
            }
        } catch (Exception e) {
            // 构造失败的结果对象
            return responseUtils.fail(500, "用户删除失败: " + e.getMessage());
        }
    }

    /**
     * 切换用户禁用状态（后台管理专用）
     * @param userId 用户ID
     * @param disabled 禁用状态
     * @return 切换结果
     */
    @PostMapping("/toggleDisabled/{userId}")
    public ResponseEntity<Result<User>> toggleUserDisabledStatus(@PathVariable int userId, @RequestParam boolean disabled, HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int userIdFromToken = JWTUtils.getUserIdFromRequest(request);
            
            // 如果无法获取用户ID，则返回错误
            if (userIdFromToken == -1) {
                return responseUtils.failWithType(401, "无法获取用户身份信息");
            }
            
            User user = webUserService.toggleUserDisabledStatus(userId, disabled);
            if (user != null) {
                String status = disabled ? "禁用" : "启用";
                return responseUtils.success(user, "用户" + status + "成功");
            } else {
                String status = disabled ? "禁用" : "启用";
                return responseUtils.failWithType(500, "用户" + status + "失败");
            }
        } catch (Exception e) {
            String status = disabled ? "禁用" : "启用";
            return responseUtils.failWithType(500, "用户" + status + "失败: " + e.getMessage());
        }
    }

}